import CryptoJS from "crypto-js";
import Cookies from "js-cookie";
function isBefore930OrAfter1501() {
  const now = new Date();
  const hour = now.getHours();
  const minute = now.getMinutes();

  // 判断是否9:30前
  if (hour < 9 || (hour === 9 && minute < 30)) {
    return true; // 9:30前
  }
  // 判断是否15:01后
  if (hour > 15 || (hour === 15 && minute >= 1)) {
    return true; // 15:01后
  }
  return false; // 9:30-15:00之间
}

function formatToHundredMillion(num, unit = "亿", isShowUnit = true) {
  const unitMap = {
    亿: 100000000,
    千: 1000,
    万: 10000,
  };
  if (typeof num !== "number" || isNaN(num)) return "0";
  return (num / unitMap[unit]).toFixed(1) + (isShowUnit ? unit : "");
}

/**
 * 节流函数
 * @param {Function} func - 要执行的函数
 * @param {number} interval - 时间间隔(ms)
 */
function throttle(func, interval) {
  let lastTime = 0;
  return function (...args) {
    const context = this;
    const now = Date.now();

    if (now - lastTime >= interval) {
      func.apply(context, args);
      lastTime = now;
    }
  };
}

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} delay - 延迟时间(ms)
 * @param {boolean} immediate - 是否立即执行
 */
function debounce(func, delay, immediate = false) {
  let timer = null;
  return function (...args) {
    const context = this;
    if (timer) clearTimeout(timer);

    if (immediate && !timer) {
      func.apply(context, args);
    }

    timer = setTimeout(() => {
      if (!immediate) {
        func.apply(context, args);
      }
      timer = null;
    }, delay);
  };
}

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}${month}${day}`;
};

/**
 * 获取当前日期和30天前的日期
 * @returns {Object} 包含当前日期和120天前日期的对象，格式为YYYYMMDD
 */
function getDateRange(range = 120) {
  const today = new Date();
  const thirtyDaysAgo = new Date(today);
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - range);

  return {
    today: formatDate(today),
    rangeDay: formatDate(thirtyDaysAgo),
  };
}

/**
 * MD5加密函数
 * @param {string} str - 需要加密的字符串
 * @returns {string} 加密后的字符串
 */
function md5(str) {
  return CryptoJS.MD5(str).toString();
}

/**
 * 设置cookie
 * @param {string} name - cookie名称
 * @param {string} value - cookie值
 * @param {object} options - 可选配置项
 */
function setCookie(name, value, options = { expires: 7, path: "/" }) {
  return Cookies.set(name, value, options);
}

/**
 * 获取cookie
 * @param {string} name - cookie名称
 * @returns {string|null} cookie值
 */
function getCookie(name) {
  return Cookies.get(name);
}

/**
 * 删除cookie
 * @param {string} name - cookie名称
 * @param {object} options - 可选配置项
 */
function removeCookie(name, options = { path: "/" }) {
  return Cookies.remove(name, options);
}

// 在导出列表中添加md5
export {
  isBefore930OrAfter1501,
  formatToHundredMillion,
  debounce,
  throttle,
  getDateRange,
  formatDate,
  md5,
  getCookie,
  setCookie,
  removeCookie,
};
